﻿using UnityEngine;
using System.Collections;

namespace Room
{
    public class RCMoveChariot : RCMoveBase
    {
        public RCMoveChariot(RoomCharactor owner)
            :base(owner)
        {
            type = MoveType.Chariot;
        }

        Vector3 target;

        

        float speed=5f;
        bool arrive = false;

        public override void SetSpeed(float speed)
        {
            this.speed = speed;
        }

        public override void DoStart()
        {
            arrive = false;
        }

        public override void Tick()
        {
            if (arrive)
                return;

            owner.transform.position = Vector3.MoveTowards(owner.transform.position, target, Time.deltaTime * speed);

            if (owner.transform.position == target)
            {
                arrive = true;
            }
        }

        public override void MoveTo(Vector3 to)
        {
            CalcY(ref to);
            target = to;
            arrive = false;
            owner.transform.LookAt(target);
        }

        public override void StopTo(Vector3 to)
        {
            CalcY(ref to);
            target = to;
            arrive = false;
            owner.transform.LookAt(target);
        }

        public void PlaceTo(Vector3 to,float angle)
        {
            target = to;
            arrive = true;
            owner.transform.position = to;
            owner.transform.eulerAngles = new Vector3(0, angle, 0);
        }
    
        public void CalcY(ref Vector3 to)
        {
            try
            {
                NavMeshHit hit;
                var y = 0f;
                if (NavMesh.SamplePosition(to, out hit, 50f, NavMesh.AllAreas))
                {
                    y = hit.position.y;
                }

                to.y = y;
            }
            catch (System.Exception e)
            {
                Debug.LogException(e);
            }
        }
    }
}